/*
 * main.cpp
 *
 *  Created on: 2009-12-21
 *      Author: Maciej Skrzypkowski
 */

#include <ctime>
#include <iostream>
#include "Log.h"
#include "server.h"
#include "messages.h"
#include <cstdlib>

int main(int argc, char **args)
{
#ifdef WIN32
	// windoz to wuj i trzeba inicjalizowa� winsocki
	// ^^ fajnie polskie litery wygladaja po przejsicu przez repozytorium, LOL
	// linux nie musi
	WSAData wsadata;
	WSAStartup(MAKEWORD(1, 1), &wsadata);
#endif


#if 1
	if(argc < 2)
	{
		std::cout << args[0] << " <port> {<hostname1> <port1> ...}" << std::endl;
		return 0;
	}

	std::list<IPAddress> servers;
	for(int i = 2; i < argc-1; i += 2)
	{
		servers.push_back(IPAddress(String(args[i]), atoi(args[i+1])));
	}

	Server *server = new Server(atoi(args[1]), servers);
	server->exec();
#else
	// run server
	if(String(args[1]) == "server")
	{
		if(argc < 3)
		{
			return 0;
		}

		std::list<IPAddress> servers;
		for(int i = 3; i < argc-1; i += 2)
		{
			servers.push_back(IPAddress(String(args[i]), atoi(args[i+1])));
		}

		Server *server = new Server(atoi(args[2]), servers);
		server->exec();
	}

	//send message to server
	else if(String(args[1]) == "client")
	{
		if(argc < 5)
		{
			return 0;
		}

		TCPConnection conn;
		conn.setIPAddress(IPAddress(String(args[2]), atoi(args[3])));
		conn.connect();

		ClientMessage greetMsg;
		greetMsg.type = MSG_GREETING;
		strncpy(greetMsg.clientName, args[4], 32);
		conn.send((uint8 *)&greetMsg, sizeof(greetMsg));
		conn.receive((uint8 *)&greetMsg, sizeof(greetMsg));

		while(1)
		{
			AnyMessage msg;
			memset(&msg, 0, sizeof(msg));

			std::cout << "type = ";
			std::cin >> msg.client.type; msg.client.type -= '0';
			std::cout << "sem = ";
			std::cin >> msg.sem.semName;

			if(msg.client.type == MSG_DEADLOCK)
			{
				std::cout << "suspect = ";
				std::cin >> msg.deadlock.suspectName;
			}

			conn.send((uint8 *) &msg, sizeof(msg));
			if(msg.client.type == MSG_EXIT)
			{
				break;
			}

			conn.receive((uint8 *)&msg, sizeof(msg));
			if(msg.client.type == MSG_SUCCESS) std::cout << "MSG_SUCCESS" << std::endl;
			else if(msg.client.type == MSG_FAILURE) std::cout << "MSG_FAILURE" << std::endl;
			else if(msg.client.type == MSG_PING)
			{
				std::cout << "MSG_PING" << std::endl;

				ClientMessage pingMsg;
				pingMsg.type = MSG_PING;
				conn.send((uint8 *)&pingMsg, sizeof(pingMsg));
			}
			else std::cout << "MSG_??? = " << (msg.client.type + '0') << std::endl;
		}
		conn.close();
	}

	else
	{
		std::cout << "Zle argumenty" << std::endl;
	}
#endif

#ifdef WIN32
	WSACleanup();
#endif

	return 0;
}
